package com.github.shiqiyue.blog.markdown.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.shiqiyue.blog.markdown.controller.base.BaseController;
import com.github.shiqiyue.blog.markdown.entity.User;
import com.github.shiqiyue.blog.markdown.service.UserService;
import com.github.shiqiyue.blog.markdown.vo.rep.base.RepBaseVO;

/***
 * user controller
 * 
 * @author wwy
 *
 */
@PreAuthorize("hasRole('USER')")
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	@Qualifier("userPasswordEncoder")
	private PasswordEncoder passwordEncoder;
	
	@GetMapping("password/modify")
	public String modifyPasswordPage() {
		return "user/passwordModify";
	}
	
	@PostMapping("password/modify")
	@ResponseBody
	public RepBaseVO modifyPassword(String oldPassword, String newPassword) {
		RepBaseVO repVO = new RepBaseVO<>();
		User user = getUser();
		boolean passwordCorrect = passwordEncoder.matches(oldPassword, user.getPassword());
		if (!passwordCorrect) {
			return repVO.setCommonFail().setMes("密码错误");
		}
		user.setPassword(passwordEncoder.encode(newPassword));
		userService.save(user);
		return repVO.setCommonSuccess();
	}
	
}
